<template>
    <el-card>
        <div class="box">
            <div class="short"></div>
            <div>我管理的团队详情</div>
        </div>
        <p>团队信息</p>
        <div class="teamInfo-container">
            <div>
                <span class="title">团队编号</span>
                <span>{{ route.query._id }}</span>
            </div>
            <div>
                <span class="title">团队名称</span>
                <span>{{ teamInfoData.name }}</span>
            </div>
            <div style="display: flex; justify-content:left; align-items: center;">
                <span class="title">团队头像</span>
                <el-image :src="teamInfoData.avatar"></el-image>
            </div>
            <div>
                <span class="title">团队标签</span>
                <el-tag v-if="tagObjects.length > 0" v-for="(item, index) in tagObjects" :key="item._id"
                    :type="getTagType(index)" round>{{ item.name }}</el-tag>

                <el-tag v-else round>无</el-tag>
            </div>
            <div style="display: flex; align-items: center;">
                <span class="title" style="width: 60px;">机构地址</span>
                <div>
                    <span>{{ teamInfoData.organizationId?.address }}</span>
                </div>
            </div>
            <div>
                <span class="title">团队评分</span>
                <span>{{ teamInfoData.rate }}</span>
            </div>
            <div>
                <span class="title">签约人数</span>
                <span>{{ teamInfoData.signNumber }}</span>
            </div>
        </div>
        <div style="display: flex; margin-top: 20px;">
            <span class="title" style="width: 55px; display: inline-block;">邀请加入二维码</span>
            <img style="width: 160px;height: 160px;" src="../../../assets/teamManage/u5951.png"></img>
        </div>
        <div>
            <span class="title" style="display:inline-block; margin-top: 20px;">创建时间</span>
            <span>{{ teamInfoData.leaderId?.roleId?.createTime }}</span>
        </div>
        <div>
            <span class="title" style="display:inline-block; margin-top: 20px;">创建人</span>
            <span>{{ teamInfoData.leaderId?.name }}</span>
        </div>
        <div class="bottom">
            <span class="title" style="display:inline-block; margin-top: 20px;">团队状态</span>
            <el-switch v-model="teamInfoData.state" active-text="启用" inactive-text="禁用" :active-value="1"
                :inactive-value="0" inline-prompt
                style="--el-switch-on-color:#13ec66; --el-switch-off-color: #ccc"></el-switch>
        </div>

        <!-- 底部操作按钮区 -->
        <el-button type="primary" @click="openDialog()">编辑团队信息</el-button>
        <el-button type="danger" @click="deleteTeam(route.query._id)">解散团队</el-button>
        <el-button @click="$router.back">返回</el-button>

        <!-- 对话框弹窗 -->
        <el-dialog v-model="open" width="400" title="编辑团队信息">
            <!-- {{ teamInfoData }} -->
            <el-form :model="teamInfoData" label-width="auto" style="max-width: 250px; margin: 0 auto;">
                <el-form-item label="团队名称">
                    <el-input placeholder="请输入" v-model="teamInfoData.name" />
                </el-form-item>
                <el-form-item label="团队头像">
                    <el-upload class="avatar-uploader" :action="`${baseURL}/images/upload`" :show-file-list="false"
                        :on-success="handleAvatarSuccess">
                        <img v-if="teamInfoData.avatar" :src="teamInfoData.avatar" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="所属机构">
                    <el-select v-model="teamInfoData.organizationId">
                        <el-option v-for="item in AgencyData" :key="item._id" :label="item.name"
                            :value="item._id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="团队标签">
                    <el-select size="large" style="width: 200px; margin-left: 15px;" placeholder="请选择"
                        v-model="teamInfoData.tagIds" :max-collapse-tags="3" collapse-tags multiple clearable>
                        <template #header>
                            <el-checkbox v-model="checkAll" :indeterminate="indeterminate" @change="handleCheckAll">
                                全选
                            </el-checkbox>
                        </template>
                        <el-option v-for="item in TagsData.rows" :key="item._id" :label="item.name" :value="item._id" />
                    </el-select>
                </el-form-item>
            </el-form>
            <div class="right">
                <el-button @click="open=false">取消</el-button>
                <el-button type="primary" @click="updateTeam()">确定</el-button>
            </div>
        </el-dialog>
    </el-card>
</template>

<script setup>
import { onMounted, ref,watch,computed} from 'vue';
import { deleteTeamApi, getTeamInfoApi, updateTeamApi } from '../../../api/teamManage';
import { useRoute } from 'vue-router';
import { findAgencyApi } from '../../../api/agency';
import { ElMessage } from 'element-plus';
import { ElMessageBox } from 'element-plus';
import { useFindData } from '../../../composables/findData';
import { Plus } from '@element-plus/icons-vue'




const baseURL = import.meta.env.VITE_BASE_URL
const route = useRoute()
const { TagsData, findTagsAsync, } = useFindData()
const checkAll = ref(false)
const indeterminate = ref(false)
//团队详情信息数据
const teamInfoData = ref({})
//机构数据
const AgencyData = ref([])
const open = ref(false)

// 计算属性：将 tagIds 映射为标签对象数组
const tagObjects = computed(() => {
    if (!teamInfoData.value.tagIds || !TagsData.rows) return [];

    return teamInfoData.value.tagIds.map(tagId => {
        const tag = TagsData.rows.find(t => t._id === tagId);
        return tag || { _id: tagId,name: `未知标签(${tagId})` };
    });
});

//定义标签颜色
function getTagType(index) {
    const types = ['danger', 'primary', 'warning',]; // Element UI 内置类型
    return types[index % types.length];
}

// 上传头像成功回调
const handleAvatarSuccess = (res) => {
    if (res.code == 200) {
        teamInfoData.value.avatar = res.data
    }
}

//对话框打开
const openDialog  = ()=>{
    open.value = true;
}

watch(() => teamInfoData.value.tagIds, (val) => {
    if (!val) return
    if (val.length === 0) {
        checkAll.value = false
        indeterminate.value = false
    } else if (val.length === TagsData.rows?.length) {
        checkAll.value = true
        indeterminate.value = false
    } else {
        indeterminate.value = true
    }
})

// 完善全选处理函数
const handleCheckAll = (val) => {
    indeterminate.value = false
    if (val) {
        teamInfoData.value.tagIds = TagsData.rows?.map(item => item._id) || []
    } else {
        teamInfoData.value.tagIds = []
    }
}

//获取团队详情信息
const getTeamInfo = async () => {
    const res = await getTeamInfoApi({ _id: route.query._id })
    console.log("------",res);
    if (res.code == 200) {
        teamInfoData.value = res.data
        teamInfoData.value.tagIds = res.data.tagIds.map(item => item._id);
        
    }
}

//查询机构方法
const findAgency = async () => {
    const res = await findAgencyApi()
    console.log(res);

    if (res.code == 200) {
        AgencyData.value = res.data.rows
    }
}

//修改团队信息
const updateTeam = async () =>{
    const res = await updateTeamApi({
        ...teamInfoData.value
    })
    console.log(res);
    if(res.code == 200){
        ElMessage({
            message: '修改成功！',
            type: 'success',
        })
    }else{
        ElMessage({
            message: res.message,
            type: 'warning',
        }) 
    }
    open.value = false
    getTeamInfo()
}


//删除团队方法
function deleteTeam(id) {
    ElMessageBox.confirm(
        '该操作不可撤销，确认解散团队吗？',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        // 调用删除API并传递医生ID
        return deleteTeamApi({ _id: id })
    }).then(res => {
        if (res.code === 200) {
            ElMessage.success('删除成功！')
        } else {
            throw new Error('删除失败')
        }
    }).catch(err => {
        if (err.name !== 'Cancel') { // 排除用户取消的情况
            console.error('删除失败：', err)
            ElMessage.error('删除失败，请重试')
        }
    })
}

onMounted(() => {
    getTeamInfo(),
    findAgency(),
    findTagsAsync()
})
</script>

<style scoped lang="scss">

.teamInfo-container {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr 1fr;
    justify-content: center;
    align-items: center;

    .el-image {
        width: 50px;
        height: 50px;
    }
}

.bottom {
    padding-bottom: 20px;
    border-bottom: 1px #eee solid;
}

.title {
    color: #999999;
    font-size: 13px;
    margin-right: 10px;
}
.right{
    display: flex;
    justify-content: flex-end;
}
.avatar-uploader {
    width: 60px;
    height: 60px;
    border-radius: 8px;
    border: 1px dashed var(--el-border-color);
    text-align: center;
    cursor: pointer;

    .avatar {
        width: 100%;
        height: 100%;
        border-radius: 8px;
    }

    .el-icon.avatar-uploader-icon {
        font-size: 20px;
        color: #5f90d4;
        width: 60px;
        height: 60px;
        text-align: center;
    }

}
</style>